﻿using MES.Server.Entities;
using MES.Server.IService;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace MES.Server.Service
{
    public class MenuService : BaseService, IMenuService
    {
        
        public MenuService(ISqlSugarClient client) : base(client)
        {

        }
        public IEnumerable<MenuEntity> GetAllMenus(string key)
        {
            // 条件 ：数据库中的记录，State>=0   ,
            //       并且

            //       （Key是空的情况，返回所有记录，
            //              或者 MenuHeader匹配这个关键词，
            //              或者 TargetView匹配这个关键词，
            //              或者 当前菜单的子菜单相关的字段（MenuHeader/TargetView）也能匹配穿上关键词）
            var ms = _Client.Queryable<MenuEntity>()
                .Where(m => m.State >= 0 &&

                (string.IsNullOrEmpty(key) ||
                    (
                      m.MenuHeader.Contains(key) ||
                      m.TargetView.Contains(key) ||

                      SqlFunc.Subqueryable<MenuEntity>().Where(sm => sm.ParentId == m.MenuId &&
                                            (sm.MenuHeader.Contains(key) || sm.TargetView.Contains(key))).Count() > 0
                    ))
                )
                .Select(m => new MenuEntity
                {
                    MenuId = m.MenuId,
                    MenuHeader = m.MenuHeader,
                    TargetView = m.TargetView,
                    ParentId = m.ParentId,
                    MenuIcon = m.MenuIcon,
                    State = m.State,
                    Funcs = m.Funcs,
                    FuncNames = !string.IsNullOrEmpty(m.Funcs) ? SqlFunc.Subqueryable<FuncEntity>()
                                             .Where(z => m.Funcs.Contains(z.FuncId.ToString()))
                                             .SelectStringJoin(z => z.FuncName, ",") : ""

                })
                .ToList();

            return ms;
        }

        public IEnumerable<MenuEntity> GetMenusByUser(int uid)
        {
            var ms = _Client.Queryable<MenuEntity>()
                .Where(m =>
                       SqlFunc.Subqueryable<RoleMenuEntity>()
                          .Where(rm =>
                                 m.MenuId == rm.MenuId.ToString() &&
                                 SqlFunc.Subqueryable<RoleUserEntity>()
                                      .Where(ru => ru.UserId == uid && rm.RoleId == ru.RoleId)
                                      .Any())
                          .Any())
                  .Select(m => m).ToArray();

            return ms;
        }
        public MenuEntity[] GetMenusByRoles(int[] ids)
        {
            // 从RoleMenu表中获取所有权限匹配菜单编号=--功能
            var mids = _Client.Queryable<RoleMenuEntity>()
                      .Where(rm => ids.Contains(rm.RoleId))
                      .Select(rm => rm.MenuId.ToString())
                      .ToArray();

            return _Client.Queryable<MenuEntity>()
                 .Where(m => mids.Contains(m.MenuId))
                 .Select(m => new MenuEntity
                 {
                     MenuHeader = m.MenuHeader,
                     MenuId = m.MenuId,
                     MenuIcon = m.MenuIcon,
                     ParentId = m.ParentId,
                     State = m.State,
                     TargetView = m.TargetView,
                     Funcs = SqlFunc.Subqueryable<RoleMenuEntity>()
                            .Where(rm => ids.Contains(rm.RoleId) && rm.MenuId.ToString() == m.MenuId)
                            .SelectStringJoin(rm => rm.MenuFuncs, ",")
                 }).ToArray();
        }
        public int Update(MenuEntity menu)
        {
            int count = 0;
            if (string.IsNullOrEmpty(menu.MenuId))
            {
                // 新增的逻辑
                var max = _Client.Queryable<MenuEntity>()
                                .Where(m => m.ParentId == menu.ParentId)
                                .Max(m => m.MenuId);
                menu.MenuId = (int.Parse(max) + 1).ToString();
                count = _Client.Insertable(menu).ExecuteCommand();
            }
            else
            {
                var menuEntity = _Client.Queryable<MenuEntity>()
                                        .Where(m => m.MenuId == menu.MenuId)
                                        .ToList().FirstOrDefault();
                if (menuEntity == null)
                    throw new Exception("没有匹配的菜单的信息");

                menuEntity.MenuHeader = menu.MenuHeader;
                menuEntity.ParentId = menu.ParentId;
                menuEntity.TargetView = menu.TargetView;
                menuEntity.MenuIcon = menu.MenuIcon;
                menuEntity.Funcs = menu.Funcs;
                count = _Client.Updateable(menuEntity).ExecuteCommand();
            }

            return count;
        }

        public int Delete(string id)
        {
            // 根据主键删除
            return _Client.Deleteable<MenuEntity>()
                .In(id).ExecuteCommand();
        }
        public int Delete(string[] ids)
        {
            // 根据主键删除
            return _Client.Deleteable<MenuEntity>()
                .In(ids).ExecuteCommand();
        }
    }
}
